package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.MemberCardRenewal;
import com.finance.mapper.MemberCardRenewalMapper;
import com.finance.service.MemberCardRenewalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C11
 * 会员卡续卡数据Service实现类
 */
@Slf4j
@Service
public class MemberCardRenewalServiceImpl extends ServiceImpl<MemberCardRenewalMapper, MemberCardRenewal> implements MemberCardRenewalService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            log.warn("No records to process for C11 data");
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                .eq(MemberCardRenewal::getSearchDate, searchDate)
                .eq(MemberCardRenewal::getCinemaId, cinemaId)
                .count();
            if (count > 0) {
                log.info("C11数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                .eq(MemberCardRenewal::getSearchDate, searchDate)
                .eq(MemberCardRenewal::getCinemaId, cinemaId)
                .remove();
        }

        List<MemberCardRenewal> renewalList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                MemberCardRenewal renewal = new MemberCardRenewal();
                renewal.setCinemaId(cinemaId);
                //发卡影城名称,发卡影城编码,续卡影城名称,续卡影城编码,订单号,续卡时间,卡号,卡类型,卡类型编码
                if (StringUtils.hasText(record.get("发卡影城名称"))) {
                    renewal.setIssueCinemaName(record.get("发卡影城名称"));
                }
                if (StringUtils.hasText(record.get("发卡影城编码"))) {
                    renewal.setIssueCinemaCode(record.get("发卡影城编码"));
                }
                if (StringUtils.hasText(record.get("续卡影城名称"))) {
                    renewal.setRenewalCinemaName(record.get("续卡影城名称"));
                }
                if (StringUtils.hasText(record.get("续卡影城编码"))) {
                    renewal.setRenewalCinemaCode(record.get("续卡影城编码"));
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    renewal.setOrderNo(record.get("订单号"));
                }
                
                // 处理续卡时间
                String renewalTimeStr = record.get("续卡时间");
                if (StringUtils.hasText(renewalTimeStr)) {
                    try {
                        renewal.setRenewalTime(LocalDateTime.parse(renewalTimeStr, DATE_TIME_FORMATTER));
                    } catch (Exception e) {
                        log.warn("Invalid renewal time format: {}", renewalTimeStr);
                    }
                }
                if (StringUtils.hasText(record.get("卡号"))) {
                    renewal.setCardNo(record.get("卡号"));
                }
                if (StringUtils.hasText(record.get("卡类型"))) {
                    renewal.setCardType(record.get("卡类型"));
                }
                if (StringUtils.hasText(record.get("卡类型编码"))) {
                    renewal.setCardTypeCode(record.get("卡类型编码"));
                }
                // 卡政策名称,卡政策编码,续卡费,支付工具,支付工具编码,续费渠道,续费渠道编码,操作员,操作员工号
                if (StringUtils.hasText(record.get("卡政策名称"))) {
                    renewal.setCardPolicyName(record.get("卡政策名称"));
                }
                if (StringUtils.hasText(record.get("卡政策编码"))) {
                    renewal.setCardPolicyCode(record.get("卡政策编码"));
                }
                
                // 处理续卡费
                String renewalFeeStr = record.get("续卡费");
                if (StringUtils.hasText(renewalFeeStr)) {
                    try {
                        renewal.setRenewalFee(new BigDecimal(renewalFeeStr));
                    } catch (Exception e) {
                        log.warn("Invalid renewal fee format: {}", renewalFeeStr);
                    }
                }
                
                if (StringUtils.hasText(record.get("支付工具"))) {
                    renewal.setPaymentTool(record.get("支付工具"));
                }
                if (StringUtils.hasText(record.get("支付工具编码"))) {
                    renewal.setPaymentToolCode(record.get("支付工具编码"));
                }
                if (StringUtils.hasText(record.get("续费渠道"))) {
                    renewal.setRenewalChannel(record.get("续费渠道"));
                }
                if (StringUtils.hasText(record.get("续费渠道编码"))) {
                    renewal.setRenewalChannelCode(record.get("续费渠道编码"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    renewal.setOperator(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("操作员工号"))) {
                    renewal.setOperatorEmployeeNo(record.get("操作员工号"));
                }
                // 工作站,会员ID
                if (StringUtils.hasText(record.get("工作站"))) {
                    renewal.setWorkstation(record.get("工作站"));
                }
                if (StringUtils.hasText(record.get("会员ID"))) {
                    renewal.setMemberId(record.get("会员ID"));
                }
                renewal.setSearchDate(searchDate);
                
                renewalList.add(renewal);
            } catch (Exception e) {
                log.error("Error processing C11 record: {}", record, e);
                throw new RuntimeException("Failed to process C11 record", e);
            }
        }

        try {
            saveBatch(renewalList);
            return renewalList.size();
        } catch (Exception e) {
            log.error("Error saving C11 data batch", e);
            throw new RuntimeException("Failed to save C11 data batch", e);
        }
    }
} 